import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;

/**
 * @ClassName MyClassLoader
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/11/7 下午9:08
 * @Version V1.0
 * @Since JDK 11
 */
public class MyClassLoader extends ClassLoader {

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if(!"Hello".equals(name)){
            return super.loadClass(name);
        }
        String path = "/home/melt/IdeaProjects/java-homework/JavaHomework/week01/L2/src";
        String filePath = path+File.separator+name+".xlass";
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            byte[] bytes = new byte[fileInputStream.available()];
            fileInputStream.read(bytes);
            //255-x
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte) (255-bytes[i]);
            }
            return defineClass(name,bytes,0,bytes.length);
        } catch (IOException e) {
            return super.loadClass(name);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> aClass = myClassLoader.loadClass("Hello");
        try {
            Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
            Object o = declaredConstructor.newInstance();
            Method hello = aClass.getDeclaredMethod("hello");
            hello.invoke(o);
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //运行结果 Hello, classLoader!
    }
}
